﻿@page "/home"
@inject IHttpClientFactory Http
@inject IJSRuntime JSRuntime
@inject NavigationManager Navigation
@inject StateService State
@inject Blazored.LocalStorage.ILocalStorageService localStorage
@attribute [Authorize]
@using Microsoft.AspNetCore.Authorization
@using lcwb.Shared.Service
<Card>
    <Row Align="RowAlign.Middle" Gutter="24">
        <Col Flex="@("1 1 200px")">
        <Typography>
            <Title Level="3" >
                <Icon Type="smile" Theme="IconThemeType.Outline" />
                欢迎回来，@State.CurrentUserName！
            </Title>
            <Paragraph>
                您已成功登录系统，可以开始使用各项功能
            </Paragraph>
        </Typography>
        </Col>
        <Col>
        <Button Danger Ghost OnClick="Logout">
            <Icon Type="logout" /> 退出登录
        </Button>
        </Col>
    </Row>
</Card>

@code {
    
    protected override async Task OnInitializedAsync()
    {
        State.OnStateChange += StateHasChanged;
        // 检查是否有有效的 JWT
        // 可以略去
        var token = await localStorage.GetItemAsync<string>("jwtToken");
        if (string.IsNullOrEmpty(token))
        {
            Navigation.NavigateTo("/login");
        }
    }
    
    public void Dispose()
    {
        State.OnStateChange -= StateHasChanged;
    }

    private async Task Logout()
    {
        // 清除 JWT
        await localStorage.RemoveItemAsync("jwtToken");

        State.CurrentUserId = 0;
        State.CurrentUserName = null;
        // 跳转到登录页面
        Navigation.NavigateTo("/login");
    }
}